import { defineStore } from 'pinia'
import {
  postUserListData,
  deleteUserById,
  newUserData,
  editUserData,
  postPageListData,
  deletePageById,
  newPageData,
  editPageData
} from '@/service/main/system/system'
import useMainStore from '../main'
import type { ISystemState } from './type'
const useSystemStore = defineStore('system', {
  state: (): ISystemState => ({
    usersList: [],
    usersTotalCount: 0,
    pageTotalCount: 0,
    pageList: []
  }),

  actions: {
    // 查询部门/角色数据
    async postUsersListAction(params?: object) {
      const userListResult = await postUserListData(params)
      const { totalCount, list } = userListResult.data
      this.usersList = list
      this.usersTotalCount = totalCount
    },
    // 删除用户(放到了组件内部用于删除后保持在当前页而非第一页)
    async deleteUserByIdAction(id: number) {
      console.log('deleteUser')
    },
    // 新增用户
    async newUserDataActive(usersInfo: any) {
      const newResult = await newUserData(usersInfo)
      console.log(newResult)
      // 新增数据默认在第一列即刷新时回到第一页
      this.postUsersListAction()
    },
    // 编辑用户
    async editUserDataActive(id: number, usersInfo: any) {
      const editResult = await editUserData(id, usersInfo)
    },

    /** 针对页面的数据：增删改查 */
    // 查询
    async postPageListAction(pageName: string, queryInfo: any) {
      const pageListResult = await postPageListData(pageName, queryInfo)
      const { totalCount, list } = pageListResult.data
      this.pageList = list
      this.pageTotalCount = totalCount

      return pageListResult
    },
    // 删除
    async deletePageByIdAction(pageName: string, id: number) {
      const deleteResult = await deletePageById(pageName, id)

      // 每次删除数据后重新请求公共数据
      const mainStore = useMainStore()
      mainStore.fetchEntireDateActive()
      return deleteResult
    },
    // 新增
    async newPageDataAction(pageName: string, usersInfo: any) {
      const newResult = await newPageData(pageName, usersInfo)
      console.log(newResult)

      // 每次新建数据后重新请求公共数据
      const mainStore = useMainStore()
      mainStore.fetchEntireDateActive()
      return newResult
      // 新增数据默认在第一列即刷新时回到第一页
    },
    // 修改编辑
    async editPageDataAction(pageName: string, id: number, usersInfo: any) {
      const editResult = await editPageData(pageName, id, usersInfo)

      // 每次编辑数据后重新请求公共数据
      const mainStore = useMainStore()
      mainStore.fetchEntireDateActive()
      return editResult
    },
    // 重置pageList, pageTotalCount
    clear() {
      this.pageTotalCount = 0
      this.pageList = []
    }
  }
})
export default useSystemStore
